package org.lemon.cla.serviceImp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.lemon.cla.pojo.ClubApplication;
import org.lemon.cla.pojo.User; // 导入 User 实体
import org.lemon.cla.mapper.ClubApplicationMapper;
import org.lemon.cla.service.IClubApplicationService;
import org.lemon.cla.service.IClubMemberService;
import org.lemon.cla.service.IUserService; // 导入 IUserService
import org.lemon.cla.dto.request.ClubApplicationSearchRequest;
import org.lemon.cla.enums.ClubApplicationStatusEnum;
import org.lemon.cla.vo.ClubApplicationVo; // 导入 ClubApplicationVo
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class ClubApplicationServiceImpl extends ServiceImpl<ClubApplicationMapper, ClubApplication> implements IClubApplicationService {

    @Autowired
    private IUserService userService; // 注入 IUserService 用于检查用户状态

    // 辅助方法：处理 ClubApplicationVo 中的申请人信息
    private ClubApplicationVo processApplicantInfo(ClubApplicationVo applicationVo) {
        if (applicationVo == null) return null;
        // 如果申请人ID为null，或者申请人被逻辑删除
        if (applicationVo.getUserId() == null || (applicationVo.getApplicantIsDeleted() != null && applicationVo.getApplicantIsDeleted())) {
            applicationVo.setApplicantUsername("未知用户");
            applicationVo.setApplicantAvatarUrl(null);
            applicationVo.setApplicantRealName("未知");
            applicationVo.setApplicantPhone(null);
            applicationVo.setApplicantEmail(null);
            applicationVo.setApplicantRole(null);
        }
        return applicationVo;
    }

    // 辅助方法：处理 ClubApplicationVo 中的审核人信息
    private ClubApplicationVo processReviewerInfo(ClubApplicationVo applicationVo) {
        if (applicationVo == null) return null;
        // 只有当 reviewerId 不为 null 时才需要处理审核人信息
        if (applicationVo.getReviewerId() != null) {
            // 如果审核人被逻辑删除
            if (applicationVo.getReviewerIsDeleted() != null && applicationVo.getReviewerIsDeleted()) {
                applicationVo.setReviewerUsername("未知审核人");
                applicationVo.setReviewerAvatarUrl(null);
                applicationVo.setReviewerRealName("未知");
                applicationVo.setReviewerPhone(null);
                applicationVo.setReviewerEmail(null);
                applicationVo.setReviewerRole(null);
            }
        } else {
            // 如果 reviewerId 本身就是 null，表示尚未审核，则清空审核人信息
            applicationVo.setReviewerUsername(null);
            applicationVo.setReviewerAvatarUrl(null);
            applicationVo.setReviewerRealName(null);
            applicationVo.setReviewerPhone(null);
            applicationVo.setReviewerEmail(null);
            applicationVo.setReviewerRole(null);
        }
        return applicationVo;
    }

    // 辅助方法：处理分页结果中的申请人和审核人信息
    private IPage<ClubApplicationVo> processApplicationInfoForPage(IPage<ClubApplicationVo> page) {
        if (page != null && page.getRecords() != null) {
            page.getRecords().forEach(vo -> {
                processApplicantInfo(vo);
                processReviewerInfo(vo);
            });
        }
        return page;
    }

    @Override
    public boolean hasPendingApplication(Long userId, Long clubId) {
        QueryWrapper<ClubApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("club_id", clubId);
        queryWrapper.eq("status", ClubApplicationStatusEnum.PENDING_REVIEW);
        return baseMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public boolean reviewClubApplication(Long applicationId, ClubApplicationStatusEnum newStatus, Long reviewerId) {
        ClubApplication application = baseMapper.selectById(applicationId);
        if (application == null) {
            return false; // 申请不存在
        }

        // 校验审核人是否存在且未被逻辑删除
        if (reviewerId != null) {
            User reviewer = userService.getById(reviewerId.intValue()); // Assuming reviewerId is Long, userId is Integer
            if (reviewer == null) {
                // 如果审核人不存在或已被逻辑删除，拒绝审核操作
                return false;
            }
        }

        application.setStatus(newStatus);
        application.setReviewTime(LocalDateTime.now());
        application.setReviewerId(reviewerId);

        return baseMapper.updateById(application) > 0;
    }

    @Override
    public ClubApplicationVo getClubApplicationVoById(Long applicationId) {
        ClubApplicationVo applicationVo = baseMapper.selectApplicationVoById(applicationId);
        processApplicantInfo(applicationVo);
        processReviewerInfo(applicationVo);
        return applicationVo;
    }

    @Override
    public IPage<ClubApplicationVo> getAllClubApplicationsVo(Page<ClubApplicationVo> page) {
        IPage<ClubApplicationVo> applicationPage = baseMapper.selectApplicationVoPage(page);
        return processApplicationInfoForPage(applicationPage);
    }

    @Override
    public IPage<ClubApplicationVo> searchClubApplicationsByConditions(Page<ClubApplicationVo> page, ClubApplicationSearchRequest request) {
        IPage<ClubApplicationVo> resultPage = baseMapper.selectApplicationVoByMultiConditions(page, request);
        return processApplicationInfoForPage(resultPage);
    }
}